#pragma once

#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include <sys/types.h>
#include <unistd.h>

namespace ThreadModule
{
    //要执行的任务
    using func_t = std::function<void(std::string name)>;
    static int number = 1;
    enum class TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };
    class Thread
    {
    private:
        //成员方法, 定义成静态的不传this指针
        static void *Routine(void *args)
        {
            //显示类型转换
            Thread *t = static_cast<Thread *>(args); //把参数给转换回来, 也就是自己this指针
            t->_status = TSTATUS::RUNNING;
            t->_func(t->Name()); //调用线程任务,传递参数
            return nullptr;
        }
        void EnableDetach() {_joinable = false; }
    public:
        Thread(func_t func)
        : _func(func)
        , _status(TSTATUS::NEW)
        , _joinable(true)
        {
            _name = "Thread-" + std::to_string(number++);
            _pid = getpid();
        }
        std::string Name() {return _name; }
        //创建线程
        bool Start()
        {
            if(_status != TSTATUS::RUNNING)
            {
                int n = ::pthread_create(&_tid, nullptr, Routine, this);
                if(n != 0) 
                    return false;
                return true;
            }
            return false;
        }
        bool Stop()
        {
            if(_status == TSTATUS::RUNNING)
            {
                int n = ::pthread_cancel(_tid); //取消线程
                if(n != 0)
                    return false;
                _status = TSTATUS::STOP;
            }
        }
        bool Join()
        {
            if(_joinable) //可等待
            {
                int n = ::pthread_join(_tid, nullptr); //进程被回收
                if(n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        void Detech()
        {
            pthread_detach(_tid);
            EnableDetach();
        }
        bool IsJoinable() {return _joinable; }
        //std::string Name() {return _name; }
        ~Thread(){}
    private:
        std::string _name; //一个线程的名字
        pthread_t _tid; //线程的tid
        pid_t _pid; //进程id
        bool _joinable; //是否等待, 分离后不可以等待
        func_t _func; //线程任务
        TSTATUS _status; //线程状态
    };

}